package com.example.producer.produce;

import com.alibaba.fastjson.JSON;
import com.example.producer.entity.Order;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * @author shuc001
 * @Date 2018/9/27 下午3:00
 */
@Component
public class AckSend {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    final RabbitTemplate.ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback() {
        @Override
        public void returnedMessage(org.springframework.amqp.core.Message message, int replyCode, String replyText, String exchange, String routingKey) {
            System.out.println("消息未送达 "+message.getMessageProperties().getDeliveryTag());
            System.out.println("save to db");
        }
    };

    final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            if(ack){
                System.out.println("确认消息 "+correlationData.getId());
            }else{
                System.out.println("未确认消息 "+correlationData.getId());
            }
        }
    };

    public void send(Order order){
        Message message = MessageBuilder.createMessage(JSON.toJSONString(order), new MessageHeaders(null));
        rabbitTemplate.setReturnCallback(returnCallback);
        rabbitTemplate.setConfirmCallback(confirmCallback);
        rabbitTemplate.convertAndSend("ack_ex","ack.x",message,new CorrelationData(order.getId()));
    }
}
